package org.yoyo.classroom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yoyo.classroom.domain.po.Permission;
import org.yoyo.classroom.request.LoginRequest;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.UserService;
import org.yoyo.classroom.utils.JwtTokenUtil;

import java.util.List;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Result> authenticateUser(@RequestBody LoginRequest loginRequest) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(authentication);

            // 获取用户的所有权限
            List<Permission> permissions = userService.findPermissionsByUsername(loginRequest.getUsername());

            Result result = new Result();
            result.setCode(HttpStatus.OK.value());
            result.setMessage("Login successful");
            result.setData(new JwtResponse(token, permissions));

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (BadCredentialsException e) {
            Result result = new Result();
            result.setCode(HttpStatus.UNAUTHORIZED.value());
            result.setMessage("Invalid username or password");

            return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage("An error occurred");

            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

class JwtResponse {
    private final String token;
    private final List<Permission> permissions;

    public JwtResponse(String token, List<Permission> permissions) {
        this.token = token;
        this.permissions = permissions;
    }

    public String getToken() {
        return token;
    }

    public List<Permission> getPermissions() {
        return permissions;
    }
}
